package cn.util.baidu.ueditor.upload;


import java.io.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.util.aliyun.AliyunOSSClientUtil;
import cn.util.baidu.ueditor.PathFormat;
import cn.util.baidu.ueditor.define.*;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class BinaryUploader {

	public static final State save(HttpServletRequest request,
								   Map<String, Object> conf) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;


		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}


		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());


		if ( isAjaxUpload ) {
			upload.setHeaderEncoding( "UTF-8" );
		}


		try {
			FileItemIterator iterator = upload.getItemIterator(request);


			while (iterator.hasNext()) {
				fileStream = iterator.next();


				if (!fileStream.isFormField())
					break;
				fileStream = null;
			}


			if (fileStream == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}


			String savePath = (String) conf.get("savePath");
			String originFileName = fileStream.getName();
			String suffix = FileType.getSuffixByFilename(originFileName);


			originFileName = originFileName.substring(0,
					originFileName.length() - suffix.length());
			savePath = savePath + suffix;


			long maxSize = ((Long) conf.get("maxSize")).longValue();


			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}


			savePath = PathFormat.parse(savePath, originFileName);


			String physicalPath = (String) conf.get("rootPath") + savePath;

			InputStream is = fileStream.openStream();

			/**
			 * 上传到阿里云：xhj添加
			 */
			//*******************开始***********************
			State storageState = null;
			try {
				Map<String,Object> map=AliyunOSSClientUtil.UploadOSS( fileStream,null,"public/",1);

				//UploadOSSUtil.uploadImgAliyun(is,fileName);

				storageState = StorageManager.saveFileByInputStream(is,
						physicalPath, maxSize);
				storageState.putInfo("state", "SUCCESS");
				//url:返回前端的访问路径，请根据自己实际情况填写
				storageState.putInfo("url",map.get("imageurl").toString());
				storageState.putInfo("title",fileStream.getName());
				storageState.putInfo("original", fileStream.getName());
			} catch (Exception e) {
				storageState.putInfo("state","图片上传失败！");
				storageState.putInfo("url","");
				storageState.putInfo("title", "");
				storageState.putInfo("original", "");
				//System.out.println("文件 "+fileName+" 上传失败!");
			}



			//********************结束**********************

			is.close();
			/*if (storageState.isSuccess()) {
				storageState.putInfo("url", PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}*/
			//System.out.println("storageState="+storageState);
			return storageState;
		} catch (FileUploadException e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}


	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
